package org.wiztools.thegreatwall;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author subwiz
 */
public class AddWallServlet extends HttpServlet {

    private static final Logger LOG = Logger.getLogger(AddWallServlet.class.getName());
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        LOG.info("Add Wall Servlet: doPost()");
        final List<String> errors = new ArrayList<String>();
        final String name = req.getParameter("name");
        final String title = req.getParameter("title");

        // Create wall:
        Wall wall = new Wall();
        wall.setWallName(name);
        wall.setWallTitle(title);
        //user id should be taken from session:
        wall.setUserId(1);
        LOG.info("wall: " + wall);

        //Set error msg:
        String nameMsg = (Validator.validName(name) && name.trim().length() < 100 ?
            null : "Enter wall name correctly with charecters less than 100");
        String titleMsg = (title != null && title.trim().length() < 500 ?
            null : "Enter wall title correctly with charecters less than 500");

        //Add in errors list:
        if (nameMsg != null) {
            errors.add(nameMsg);
        }
        if (titleMsg != null) {
            errors.add(titleMsg);
        }
        req.setAttribute("wall", wall);

        //Dispatch:
        if (errors.size() == 0) {
            try {
                LOG.info("Add Wall Servlet: doPost(): Adding new user");
                new MySQLOperations().addWall(wall);
            } catch (OperationException ex) {
                errors.add(ex.getMessage());
                LOG.log(Level.SEVERE, null, ex);
            }
            req.setAttribute("errors", errors.size() > 0 ? errors : null);
            doGet(req, resp);
        } else {
            req.setAttribute("errors", errors);
            req.getRequestDispatcher("/addwall.jsp").forward(req, resp);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            LOG.info("Add Wall Servlet: doGet()");
            req.getRequestDispatcher("/walls").forward(req, resp);
    }


}
